#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define N 5
typedef struct Student
{
    char name[15];
    char no[10];
    int age;
    char address[20];
}Stu;
void readInfo();
void saveInfo(Stu stu[],int n);
void readline(int num);
int main()
{
    Stu stu[N];
    int i,num;
    printf("Please input infomation:\n");
    for(i=0;i<N;i++)
    {
        scanf("%s%s%d%s",stu[i].name,stu[i].no,&stu[i].age,stu[i].address); //此处结构体变量的下标值不能遗漏，否则会出现不明乱码问题
    }
    saveInfo(stu,N);
    printf("The infomation:\n");
    readInfo();
    printf("Please enter the number of line you want to read:\n");
    scanf("%d",&num);
    readline(num);
    return 0;
}
void saveInfo(Stu stu[],int n)
{
    FILE *fp=NULL;
    int i;
    fp=fopen("file\\stu.dat","wb"); //此处需保证该程序的同层次下有个名为file的文件名，否则会无法打开要写入的文件
    if(fp==NULL)
    {
        printf("Open file want to save failed!");
        exit(-1);
    }
        for(i=0;i<n;i++)
        {
            if(fwrite(&stu[i],sizeof(Stu),1,fp)!=1) //fwrite函数以二进制的方式读取文件
                {
                    printf("Save failed!");
                    exit(-1);
                }
        }
    fclose(fp);  //关闭已打开的文件，防止数据意外丢失
}
void readInfo()
{
    Stu stu;
    FILE *fp=NULL;
    fp=fopen("file\\stu.dat","rb");
    if(fp==NULL)
    {
        printf("Open the file want to read failed!");
        exit(-1);
    }
    while(!feof(fp))
    {
        if(fread(&stu,sizeof(Stu),1,fp)==1)
        {
            printf("%s %s %d %s\n",stu.name,stu.no,stu.age,stu.address);
        }
    }
    fclose(fp);     //关闭已打开的文件，防止数据意外丢失
}
void readline(int num)  //读取指定所在行的学生的信息
{
    Stu stu;
    int offset;
    FILE *fp;
    fp=fopen("file\\stu.dat","rb");
    if(fp==NULL)
    {
        printf("Open the file want to read failed!");
        exit(-1);
    }
    offset=sizeof(Stu)*num;
    fseek(fp,offset,SEEK_SET);
    fread(&stu,sizeof(Stu),1,fp);
    printf("%s %s %d %s\n",stu.name,stu.no,stu.age,stu.address);
    fclose(fp); //一定要关闭已打开的文件
}
/*
zhangsan 10009 21 guangdong
lisi 10005 18 shanghai
wuyi 2900 20 jingzhou
xiaoye 202004 22 maoming
liming 20031 21 hangzhou
*/
